<template>
  <div class="member-table">
    <el-table
      :data="userList"
      @selection-change="onSelectionChanged"
      border
      v-loading="tableLoading"
    >
      <el-table-column align="center" type="selection" />
      <el-table-column align="center" fixed width="50" type="index" label="序号" />
      <el-table-column prop="realname" align="center" width="120" label="姓名" />
      <el-table-column prop="gender" align="center" width="100" label="性别">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.gender==1">男</el-tag>
          <el-tag v-else-if="scope.row.gender==2">女</el-tag>
          <el-tag v-else>未知</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="deptName" align="center" width="200" label="部门" />
      <el-table-column prop="duty" align="center" width="150" label="职务" />
      <el-table-column prop="jobNumber" align="center" width="200" label="员工编号" />
      <el-table-column align="center" width="200" label="排序">
        <template slot-scope="scope">
          <el-input-number
            v-focus
            :ref="scope.row.userId"
            @change="editSortChange(scope.row)"
            @keyup.enter.native="editSortBlur(scope.row)"
            @blur="saveSort(scope.row)"
            v-if="scope.row.sortEdit"
            v-model="scope.row.sort"
          />
          <div v-else>
            <label>{{scope.row.sort}}</label>
            <el-button @click="editSort(scope.row)" style="marginLeft:12px" type="text">修改</el-button>
          </div>
        </template>
      </el-table-column>
      <el-table-column align="center" min-width="200" label="操作">
        <template slot-scope="scope">
          <el-button type="text" @click="showChangePassword(scope.row.userId)">修改密码</el-button>
          <el-button type="text" @click="showUserDetailInfo(scope.row.userId)">一人一档</el-button>
          <el-button type="text" @click="deleteUser(scope.row.userId)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      @size-change="pageSizeChange"
      @current-change="pageIndexChange"
      :current-page.sync="pageIndex"
      :page-sizes="[10, 20, 50]"
      :page-size="pageSize"
      :total="totalCount"
      layout="total, sizes, prev, pager, next, jumper"
    ></el-pagination>

    <change-password v-if="changePasswordVisible" ref="changePassword" @refreshDataList="reload()"></change-password>
    <user-detail-info v-if="userDetailInfoVisible" ref="userDetailInfo" @refreshDataList="reload()"></user-detail-info>
  </div>
</template>

<script>
import UserDetailInfo from '../user-detail-info'
import ChangePassword from '../change-password'
export default {
  name: 'memberTable',
  components: {
    UserDetailInfo,
    ChangePassword
  },
  props: {
    condition: {
      type: Object,
      required: false,
      default: null
    },
    deptId: {
      type: String,
      required: false,
      default: 0
    }
  },
  data() {
    return {
      selectionList: [],
      userList: [],
      pageIndex: 1,
      pageSize: 10,
      totalCount: 0,
      tableLoading: false,
      userListSelections: [],
      isSearch: false,
      changePasswordVisible: false,
      userDetailInfoVisible: false
    }
  },
  directives: {
    // 注册一个局部的自定义指令 v-focus
    focus: {
      // 指令的定义
      inserted: function(el) {
        // 聚焦元素
        el.querySelector('input').focus()
      }
    }
  },
  methods: {
    // 排序修改
    editSort(user) {
      this.$set(user, 'sortEdit', true)
      this.$nextTick(() => {
        this.$refs[user.userId].focus()
      })
    },
    editSortChange(user) {
      this.$set(user, 'sortEditChanged', true)
    },
    async saveSort(user) {
      if (!user.sortEditChanged) {
        this.$set(user, 'sortEdit', false)
        this.$set(user, 'sortEditChanged', false)
        return
      }

      let res = await this.$http.post('/usercenter-admin/user/updateUserSort', {
        userId: user.userId,
        sort: user.sort
      })
      if (res && res.code === 200) {
        this.$set(user, 'sortEdit', false)
        this.$set(user, 'sortEditChanged', false)
        this.$notify.success({ title: '成功', message: '修改排序成功' })
        this.loadUserList()
      } else {
        this.$notify.error({ title: '错误', message: res.msg })
      }
    },
    editSortBlur(user) {
      this.$refs[user.userId].blur()
    },
    // 个人信息
    showUserDetailInfo(userId) {
      this.userDetailInfoVisible = true
      this.$nextTick(() => {
        this.$refs.userDetailInfo.init(this.dept, userId)
      })
    },
    // 修改密码
    showChangePassword(id) {
      this.changePasswordVisible = true
      this.$nextTick(() => {
        this.$refs.changePassword.init(id)
      })
    },
    onSelectionChanged(val) {
      this.selectionList = val
      this.$emit('selectionChanged', val)
    },
    // 分页
    pageIndexChange(val) {
      this.pageIndex = val
      if (this.isSearch) {
        this.loadUserListByCondition()
      } else {
        this.loadUserList()
      }
    },
    pageSizeChange(val) {
      this.pageSize = val
      this.pageIndex = 1
      this.pageIndexChange(1)
    },
    reload() {
      this.$nextTick(() => {
        this.pageIndex = 1
        if (this.isSearch) {
          this.loadUserListByCondition()
        } else {
          this.loadUserList()
        }
      })
    },
    // 加载
    async loadUserList() {
      this.tableLoading = true
      let res = await this.$http.post(
        '/usercenter-admin/dept/getUserByDeptId',
        {
          page: this.pageIndex,
          limit: this.pageSize,
          deptId: this.deptId
        }
      )

      if (res.code === 200) {
        this.totalCount = res.data.totalCount
        this.userList = res.data.list
      } else {
        this.$notify.error({title: '失败', message: '加载人员列表失败，请重试！'})
      }
      this.tableLoading = false
    },
    async loadUserListByCondition() {
      let request = Object.assign(JSON.parse(JSON.stringify(this.condition)), {
        page: this.pageIndex,
        limit: this.pageSize
      })
      delete request.deptIds
      this.tableLoading = true
      let res = await this.$http({
        method: 'post',
        url: '/usercenter-admin/user/list',
        data: request
      })
      if (res.code === 200) {
        this.totalCount = res.data.totalCount
        this.userList = res.data.list
      } else {
        this.$notify.error({title: '失败', message: '加载人员列表失败，请重试！'})
      }
      this.tableLoading = false
    },
    async multiDeleteUser() {
      var idList = this.selectionList.map(x => x.userId)
      if (idList.length <= 0) {
        this.$notify.warning({title: '提示', message: '没有选中任何项'})
        return
      }

      let confirm = await this.$confirm(`确定要进行批量删除操作吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      if (confirm !== 'confirm') return

      let res = await this.$http({
        url: '/usercenter-admin/user/delete',
        method: 'post',
        data: { ids: this.selectionList.map(x => x.userId).join(',') }
      })
      if (res && res.code === 200) {
        this.$notify.success({ title: '成功', message: '操作成功' })
        this.pageIndex = 1
        this.loadUserList()
        this.$store.dispatch('user/loadAlertListCount')
      } else {
        this.$notify.error({ title: '错误', message: res.msg })
      }
    },
    // 删除
    async deleteUser(id) {
      let confirm = await this.$confirm(`确定要进行删除操作吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      if (confirm !== 'confirm') return

      let res = await this.$http({
        url: '/usercenter-admin/user/delete',
        method: 'post',
        data: { ids: id }
      })
      if (res && res.code === 200) {
        this.$notify.success({ title: '成功', message: '操作成功' })
        this.pageIndex > 1 && this.userList.length <= 1 && this.pageIndex--
        this.loadUserList()
        this.$store.dispatch('user/loadAlertListCount')
      } else {
        this.$notify.error({ title: '错误', message: res.msg })
      }
    }
  },
  watch: {
    condition(val) {
      if (val) {
        this.isSearch = true
        this.pageIndex = 1
        this.loadUserListByCondition()
      } else {
        this.isSearch = false
        this.pageIndex = 1
        this.loadUserList()
      }
    },
    deptId(val, oldVal) {
      this.pageIndex = 1
      this.loadUserList()
    }
  },
  created() {
    if (this.isSearch) {
      this.loadUserListByCondition()
    } else {
      this.loadUserList()
    }
  }
}
</script>

<style>
</style>
